// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	"flag"
	"fmt"
	"log"
	"net/http"
)

var addr = flag.String("addr", ":8080", "http service address")

func serveHome(w http.ResponseWriter, r *http.Request, hub *Hub) {
	if r.URL.Path == "/websocket/http/html" {
		http.ServeFile(w, r, "home.html")
		return
	} else if r.URL.Path == "/websocket/http/push" {
		from := r.PostFormValue("f")
		to := r.PostFormValue("t")
		content := r.PostFormValue("c")
		hub.broadcast <- []byte(fmt.Sprintf(`{"f":"%s","t":"%s","c":"%s"}`, from, to, content))
	} else {
		http.Error(w, "Not found", http.StatusNotFound)
		return
	}
}
func main() {
	flag.Parse()
	hub := newHub()
	go hub.run()
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		serveHome(w, r, hub)
	})
	http.HandleFunc("/websocket/client", func(w http.ResponseWriter, r *http.Request) {
		serveWs(hub, w, r)
	})
	err := http.ListenAndServe(*addr, nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
